package cn.com.zhuxulin.android.demos.activities;

import cn.com.zhuxulin.android.demos.R;
import cn.com.zhuxulin.android.demos.R.id;
import cn.com.zhuxulin.android.demos.R.layout;
import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SharedPreference extends Activity {
	private SharedPreferences sharePreferences = null;
	private int age = 0;
	private TextView showInfo = null;
	private Button read = null;
	private Button write = null;
	private Editor editor = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shared_preference);
		showInfo = (TextView) findViewById(R.id.showSharedPreferences);
		read = (Button) findViewById(R.id.read);
		write = (Button) findViewById(R.id.write);
		sharePreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
		editor = sharePreferences.edit();
	}

	@Override
	public void onStart() {
		super.onStart();
		read.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Person.name = sharePreferences.getString("name", "null");
				Person.age = sharePreferences.getInt("age", 0);
				showInfo.setText("Name:" + Person.name + "\nAge:" + Person.age);
			}
		});
		write.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				editor.putString("name", "ZhuXulin");
				editor.putInt("age", age);
				editor.commit();
				age++;
			}
		});
	}

	private static class Person {
		static String name = "";
		static int age = -1;
	}
}